package com.seeyon.apps.ext.ObxMsgPush.utils;
import java.io.IOException;
import java.net.InetAddress;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

import javax.net.ssl.SSLContext;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;


public class HttpUtil {

//    static CloseableHttpClient httpClient;
//    static CloseableHttpResponse httpResponse;
    private static final Log logger = LogFactory.getLog(HttpUtil.class);


    public static CloseableHttpClient createSSLClientDefault() {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                    public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                        return true;
                    }
            }).build();
//            HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        return HttpClients.createDefault();
    }

    /**
     * 发送https请求
     * @param
     * @throws Exception
     */
    public static String sendByHttp(String url,Map<String, Object> header,String params) {
    	CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        try {
            /*请求头*/
//        	logger.info(url);
            HttpPost httpPost = new HttpPost(url);
            if(header!=null) {
            	for (String key : header.keySet()) {
            		httpPost.addHeader(key,header.get(key).toString());
                }
            }
            if(params!=null) {
//            	logger.info(params);
            	StringEntity entity=new StringEntity(params, Consts.UTF_8);
                 //设置请求参数
            	httpPost.setEntity(entity);
            }
            httpClient = HttpUtil.createSSLClientDefault();
            httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                String jsObject = EntityUtils.toString(httpEntity, "UTF-8");
                return jsObject;
            } else {
                return null;
            }
        } catch (Exception e) {
//        	try {
//        		String ip = InetAddress.getByName("yunzhijia.com").getHostAddress();
//        		logger.info(ip);
//			} catch (Exception e2) {
//				e2.printStackTrace();
//			}
            e.printStackTrace();
            return null;
        } finally {
            try {
            	if(httpResponse!=null) {
            		httpResponse.close();
            	}
            	if(httpClient!=null) {
            		httpClient.close();
            	}
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
	 * 处理发送application/x-www-form-urlencoded格式的post请求
	 * @param url
	 * @param params
	 * @return
	 */
	public static String sendPost(String url,Map<String, String> params)  {
		try {
			PostMethod postMethod = null;
	        postMethod = new PostMethod(url) ;
	        postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8") ;
	        //参数设置，需要注意的就是里边不能传NULL，要传空字符串 
	        //key  value 形式参数
	        NameValuePair[] data =new NameValuePair[params.size()];
	        if(params!=null) {
	        	int i=0;
            	for (String key : params.keySet()) {
            		NameValuePair nameValuePair = new NameValuePair(key,params.get(key).toString());
            		data[i]=nameValuePair;
            		i++;
                }
            }
	        postMethod.setRequestBody(data);
	        HttpClient httpClient = new HttpClient();
	        httpClient.executeMethod(postMethod); // 执行POST方法
	        String result = postMethod.getResponseBodyAsString() ;  //返回结果
	        return result;
		}catch(Exception e){
			return null;
		}
	}
}